<template>
  <div class="detail">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账户设置">
          <el-form
            ref="form"
            label-width="100px"
            class="form"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="姓名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit">更新</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <Info :user-info="initUserInfo" @updateUser="updateUser" />
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <Job />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser, sysUserPut } from '@/api/user.js'
// import Info from './components/Info.vue'
export default {
  components: {
    //   异步组件使用(路由上使用叫路由懒加载，在组件上使用叫异步组件)
    Info: () => import('./components/Info.vue'),
    Job: () => import('./components/Job.vue')
  },
  data() {
    return {
      id: this.$route.params.id,
      userInfo: '',
      initUserInfo: '',
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '必填项', trigger: 'change' }],
        password: [
          { required: true, message: '必填项', trigger: 'change' },
          { min: 6, max: 12, message: '密码长度为6-12位', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    const res = await sysUser(this.id)
    // console.log(res)
    this.userInfo = res.data
    // 用户名的回显
    // 深拷贝一份用户信息传递给子组件
    this.initUserInfo = JSON.parse(JSON.stringify(res.data))
    // 用户名的回显
    this.form.username = res.data.username
  },
  methods: {
    //   更新点击
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          // 这个接口要求传入完整的用户信息
          await sysUserPut({ ...this.userInfo, ...this.form })
          //   也要将用户名同步到initUserInfo
          this.initUserInfo.username = this.form.username
          this.$message.success('修改用户信息成功')
        }
      })
    },
    // 用于子组件更新用户名
    updateUser(obj) {
      this.form.username = obj.username
      this.userInfo = JSON.parse(JSON.stringify(obj))
    }
  }
}
</script>

<style lang="scss" scoped>
.detail {
  padding: 15px;
  .form {
    margin: 0 auto;
    width: 600px;
  }
}
</style>
